package org.zjx.app.action.gather;


import lombok.SneakyThrows;
import org.zjx.analysis.analyze.window.impl.InventorAnalysis;
import org.zjx.analysis.analyze.window.impl.ItemDescriptionAnalysis;
import org.zjx.analysis.util.StringMatcherUtil;
import org.zjx.command.entity.ItemInstance;
import org.zjx.command.entity.ItemTemplate;
import org.zjx.command.enums.SlotType;
import org.zjx.command.state.ItemState;
import org.zjx.window.action.Action;
import org.zjx.window.operation.WindowOperation;
import org.zjx.window.window.IWindow;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InventorDescriptionAction extends Action {
    private final InventorAnalysis inventorAnalysis;

    public InventorDescriptionAction(IWindow targetWindow, InventorAnalysis inventorAnalysis) {
        super(targetWindow, false);
        this.inventorAnalysis = inventorAnalysis;
    }

    @Override
    public void doExecute() throws Exception {
        ItemState itemState = stateManager.getState(ItemState.class);
        List<ItemInstance> itemInstances = itemState.getItemsByType(SlotType.INVENTORY);
        for (int i = 0; i < itemInstances.size(); i++) {
            ItemInstance itemInstance = itemInstances.get(i);
            if (itemInstance == null || itemInstance.isGather()) continue;
            if (itemInstance.getTemplate().isGather()) continue;
            Rectangle itemArea = inventorAnalysis.getItemIndexArea(i);
            targetWindow.actions().gameMoveTo(itemArea.getCenterX(),itemArea.getCenterY()).delay(500);
            targetWindow.flushScreenshot();
            ItemDescriptionAnalysis itemDescriptionAnalysis = new ItemDescriptionAnalysis(targetWindow);
            String ss = itemDescriptionAnalysis.getDescription();
            matchResult(itemInstance, ss);
        }
    }


    @SneakyThrows
    public void matchResult(ItemInstance instance, String description) {
        StringMatcherUtil.MatchResult result = StringMatcherUtil.matchString(instance.getTemplate().getDescription(), description);
        if (!result.isMatched()) return;
        Map<String, Object> map = new HashMap<>();
        for (StringMatcherUtil.Keyword keyword : result.getKeywords()) {
            map.put(keyword.getPlaceholder(), keyword.getKeyword());
        }
        if (instance.getTemplate().getName().contains("合成旗")) {
            String cityName = (String) map.get("场景");
            targetWindow.actions().click(2).delay(800);
            targetWindow.flushScreenshot();
            new GatherFlagAction(targetWindow, cityName, map).doExecute();
        }
        instance.setAttributes(map);
        instance.setGather(true);
    }
}
